import { defineStore } from "pinia";
import qs from "qs";
import { post } from "@/utils/request";
import cookie from "js-cookie";
import router from "@/router";
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore({
    id:"userStore",
    persist:true, //持久化
    state:()=>({
        user: new UserInfo()
    }),
    actions:{
       setUser(user:UserInfo) {
          this.user = user
       },
       loginOut() {
        let _this = this
        const data = {
            _gp: 'admin',
            _mt: 'logout'
        }
        post(data).then((res: any) => {
            if (200 == res.errno) {
                ElMessage.success("退出成功")
                _this.user = null    //将存储的数据清空
                cookie.remove('token')//清除令牌
                router.replace('/login')//跳转到登录页面
            } else {
                ElMessage.error(res.errmsg)
                router.replace('/login')
            }
        }).catch(error => {
            console.log(error)
        })
     }
    }
})

class UserInfo {
    avatarUrl?:string;
    gmtCreate:number;
    gmtLastLogin:string;
    gmtUpdate:number;
    id:number;
    lastLoginIp:string;
    perms:string[];
    phone:string;
    realname:string;
    roleIds:number[];
    roles:string[];
    status:number;
    username:string;
    password:string;
    constructor(){
        this.avatarUrl = "";
        this.gmtCreate = 0;
        this.gmtLastLogin = "";
        this.gmtUpdate = 0;
        this.id = 0;
        this.lastLoginIp = "";
        this.perms = [];
        this.phone = "";
        this.realname = "";
        this.roleIds = [];
        this.roles = [];
        this.status = 0;
        this.username = "";
        this.password = "";
    }
}